<?php

namespace app\service;

use app\model\DelayOrderTaskModel;
use app\tool\SingletonTrait;

class DelayStatService
{
    use SingletonTrait;

    /**
     * 延期统计
     * @param array $param 查询条件
     * @param array $page  分页参数
     * @return array
     */
    public function getList(array $param, array $page): array
    {
        //基础查询
        $baseSql = (new DelayOrderTaskModel())
            ->alias('dot')
            ->join('task', 'task.id = dot.task_id');
        //组装--查询条件
        $baseSql = $this->clearDelayCondition($baseSql, $param);

        //查询类型
        switch ($param['query_type']) {
            //延期任务次数
            case 'delay_task_count':
                $baseSql->field('dot.delay_reason_type, dot.step_category_id,  count(distinct dot.task_id) num')
                    ->group("dot.delay_reason_type,dot.step_category_id");
                break;
            //延期单次数
            case 'delay_order_count':
                $baseSql->field('dot.delay_reason_type, dot.step_category_id, count(dot.delay_order_id) num')
                    ->group("dot.delay_reason_type,dot.step_category_id");
                break;
            //任务延期次数大于1
            case 'repeat_task_count':
                //延期次数大于1
                $baseSql->field('dot.task_id, count(dot.id) num')
                    ->group('dot.task_id')
                    ->having('num > 1');
                break;
            default:
                $baseSql->field("dot.delay_order_id,dot.delay_reason_type,dot.step_category_id,dot.task_id");
                break;
        }

        return $baseSql->page($page[0], $page[1])->select()->toArray();
    }

    /**
     * 处理延期统计筛选条件
     * @param $q
     * @param $param
     * @return mixed
     */
    public function clearDelayCondition($q, $param)
    {
        //过滤任务--取消状态
        $closedStatusId = StatusService::getInstance()->byCode('closed')['id'];
        //基础条件
        $q->whereIn("dot.type", ['request_delay', 'work_order']);
        $q->whereRaw("get_json_string(task.`json`, '$.task_status') <> $closedStatusId");

        //项目ID
        if (!empty($param['project_id'])) {
            $q = $q->whereIn('dot.project_id', $param['project_id']);
        }

        //时间范围
        if (!empty($param['start_time']) && !empty($param['end_time'])) {
            $q = $q->whereBetween("dot.created", [$param['start_time'], $param['end_time']]);
        }

        //阶段
        //环节ID
        if (!empty($param['step_category_id'])) {
            $q = $q->whereIn('dot.step_category_id', explode(',', $param['step_category_id']));
        }

        return $q;
    }

}
